package com.luomo.java.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author LiuMei
 * @date 2021-04-12.
 */
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        while (!atomicReference.compareAndSet(null, Thread.currentThread())) {
            //System.out.println(Thread.currentThread().getName() + "正在获取锁...");
        }
        System.out.println(Thread.currentThread().getName() + "获取锁成功");
    }

    public void myUnLock() {
        atomicReference.compareAndSet(Thread.currentThread(), null);
        System.out.println(Thread.currentThread().getName() + "释放锁");
    }

    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(() -> {
            try {
                spinLockDemo.myLock();
                System.out.println(Thread.currentThread().getName() + "在处理");
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLockDemo.myUnLock();
            }
        }, "A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            try {
                spinLockDemo.myLock();
                System.out.println(Thread.currentThread().getName() + "在处理");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLockDemo.myUnLock();
            }
        }, "B").start();
    }

}
